<template>
  <div class="app-container">
    <el-row>
      <el-col>
        <el-button icon="el-icon-arrow-left" type="text" @click="goBack">返回</el-button>
        <span>|填写{{ this.$route.query.securityType == 1 ? "项目日志" : "个人日志" }}</span>
      </el-col>
      <el-col style="margin-top: 25px; margin-left: 18px; display: flex" v-if="isToday">
        <div>日期：{{ this.form.securityDate || this.$route.query.day }}</div>
        <div style="margin-left: 50px">
          类型：{{ this.$route.query.securityType == 1 ? "项目日志" : "个人日志" }}
        </div>
        <div style="margin-left: 65%">
          风力：{{ watcher.windpower }}级 气温：{{ watcher.temperature }}°C
          天气：{{ watcher.weather }}
        </div>
      </el-col>
      <el-col style="
          margin-top: 25px;
          margin-left: 18px;
          display: flex;
          justify-content: space-between;
          margin-bottom: 10px;
        ">
        <div style="font-size: 20px">质量检查记录</div>
        <el-button style="margin-right: 60px" type="primary" size="small" @click="update" v-if="!mode">
          添加检查记录
        </el-button>
      </el-col>
    </el-row>
    <el-table :data="tableData" style="width: 100%">
      <el-table-column prop="questionDesc" label="问题描述"> </el-table-column>
      <el-table-column prop="questionBeyond" label="问题类型">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.list_quality_question_beyond" :value="scope.row.questionBeyond"/>
        </template>
      </el-table-column>
      <el-table-column prop="dutyAreaName" label="质量问题分类"></el-table-column>
      <el-table-column prop="rectificationDeadlineStatus " label="整改期限">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.list_quality_rectification_deadline_status" :value="scope.row.rectificationDeadlineStatus "/>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="质量问题提交时间"></el-table-column>
      <el-table-column prop="reviseTheDates" label="整改截至时间"></el-table-column>
      <!-- <el-table-column prop="checkTime" label="检查时间" align="center"> </el-table-column>
      <el-table-column prop="checkPeopleNickName" label="安全员" align="center"> </el-table-column>
      <el-table-column prop="hiddenClass" label="事故隐患" align="center"></el-table-column>
      <el-table-column prop="reviseTheDates" label="整改期限" align="center"></el-table-column>
      <el-table-column prop="revisePeopleNickName" label="整改负责人" align="center"></el-table-column>
      <el-table-column prop="reviseRequire" label="隐患内容" align="center"> </el-table-column> -->
      <!-- <el-table-column label="详情" align="center">
        <template slot-scope="scope">
          <el-button type="" @click="listLook(scope.row)"> 隐患详情 </el-button>
        </template>
      </el-table-column>
      <el-table-column prop="hiddenDangerStatus" label="状态" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.hiddenDangerStatus | filterStatus(dict.type.biz_check_result) }}</span>
        </template>
      </el-table-column> -->
      <el-table-column label="操作" align="center" v-if="!mode">
        <template slot-scope="scope">
          <el-button type="text" icon="el-icon-delete" @click="delRow(scope.row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-form style="margin-top: 20px" ref="form" :model="form" label-width="120px">
      <el-form-item label="施工情况补录：">
        <el-input type="textarea" :rows="4" v-model="form.constructionSupplement" :disabled="mode == 'view'"></el-input>
      </el-form-item>
      <el-form-item label="特殊情况补录：">
        <el-input type="textarea" :rows="4" v-model="form.specialSupplement" :disabled="mode == 'view'"></el-input>
      </el-form-item>
      <el-form-item label="现场照片：">
        <image-upload v-if="!mode" v-model="form.attachList" />
        <template v-else>
          <div>
            <el-image class="previewImg" v-for="item in previewList" :key="item" :src="item" fit="fill" :lazy="true"
              :preview-src-list="previewList"></el-image>
          </div>
        </template>
      </el-form-item>
      <el-form-item v-if="!mode">
        <el-button type="primary" @click="submitForm">保存</el-button>
        <el-button @click="$router.push({ name: 'Log' })">取消</el-button>
      </el-form-item>
    </el-form>
    <!-- 添加巡检记录 -->
    <el-dialog :title="title" :visible.sync="dialogVisible" width="70%" :close-on-click-modal="false">
      <el-form ref="form" :model="queryParams" label-width="120px" inline>
        <el-form-item label="检查人:">
          <el-select v-model="queryParams.checkPeopleId" placeholder="请选择检查人">
            <el-option v-for="(item, index) in revisePeopleList" :key="index" :value="item.userId"
              :label="item.nickName"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="检查类型:">
          <treeselect style="width: 200px;" v-model="queryParams.checkType" :options="deptOptions"
            :default-expand-level="100" placeholder="请选择检查类型" />
        </el-form-item>
        <el-form-item label="检查结果:">
          <el-select v-model="queryParams.dataStatus" placeholder="全部">
            <el-option v-for="item in dict.type.biz_check_result" :key="item.dictLabel" :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="queryParams.pageNum = 1, getlistLogFun()">查询</el-button>
          <el-button @click="resetFun">重置</el-button>
        </el-form-item>
      </el-form>
      <el-table :data="addtableData" style="width: 100%" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="checkTime" label="检查时间"> </el-table-column>
        <el-table-column prop="checkPeopleName" label="检查人"> </el-table-column>
        <el-table-column prop="dataSource" label="数据来源">
          <template slot-scope="scope">
            <span>{{ scope.row.dataSource | filterStatus(dict.type.list_quality_data_source) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="questionDesc" label="问题描述" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="checkTypeName" label="检查类型"></el-table-column>
        <el-table-column prop="dataStatus" label="状态">
          <template slot-scope="scope">
            <span>{{ scope.row.dataStatus | filterStatus(dict.type.biz_check_result) }}</span>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize" />
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitTable">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 隐患详情 -->
    <el-dialog width="45%" title="隐患详情" :visible.sync="innerVisible" append-to-body>
      <DialogLook v-if="innerVisible" :id="selectRow.id" />
    </el-dialog>
  </div>
</template>
<script>
import {
  getlistLog,
  getlistLogData,
  getlistData,
  listDataLook,
  listDataDel,
  upData,
  getLog,
  updateLog,
} from "@/api/biz/security/addLog"
import { getRevisePeople } from "@/api/biz/ledger/ledger"
import { getTree } from "@/api/biz/enter/enterNext"
import DialogLook from "@/components/dialogLook/index.vue"
import { mapState } from "vuex"
import Treeselect from "@riophae/vue-treeselect"
import "@riophae/vue-treeselect/dist/vue-treeselect.css"
export default {
  name: "addLog",
  components: { DialogLook, Treeselect },
  dicts: ["biz_check_result","list_quality_data_source","list_quality_rectification_deadline_status","list_quality_question_beyond"],
  filters: {
    filterStatus: function (value, data) {
      const obj = data.find(
        (item) => item.value == value
      )
      return obj?.label || ''
    },
  },
  data () {
    return {
      baseUrl: process.env.VUE_APP_BASE_API,
      mode: null, // view为查看模式
      innerVisible: false,
      selectRow: {},
      watcher: {
        windpower: null,
        temperature: null,
        weather: null,
      },
      tableData: [],
      beforTableData: [],
      addtableData: [],
      form: {},
      revisePeopleList: [],
      deptOptions: [],
      dialogVisible: false,
      title: null,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        projectId: this.$store.state.app.selectData,
        recordIds: [],
        checkType: null,
        dataStatus: '',
        checkPeopleId: '',
        time: null
      },
      total: 0,
      previewList: []
    }
  },
  methods: {
    goBack () {
      this.$store.state.tagsView.visitedViews =
        this.$store.state.tagsView.visitedViews.filter(
          (item) => item.name !== "addLog"
        )
      this.$router.go(-1)
      // if (!this.mode) {
      //   this.$router.push({ name: 'Log' })
      // } else {
      //   this.$router.push({ name: 'LogStatProject' })
      // }
    },
    generatePreviewList () {
      if (!this.form.secnePhoto || !this.form.secnePhoto.length) {
        return
      }
      const urlArray = this.form.secnePhoto.split(",")
      this.previewList = urlArray.map(item => this.baseUrl + item)
      console.log(this.previewList)
    },
    getWatchers () {
      //获取定位
      this.$axios({
        url: "https://restapi.amap.com/v3/weather/weatherInfo",
        method: "get",
        params: {
          key: "57d482def3c7fa66c2ae4f2bd950fdd6",
          city: "长春",
        },
      }).then((res) => {
        this.watcher = res.data.lives[0]
      })
    },
    //添加巡检记录
    async update () {
      if (this.queryParams.projectId == null) {
        this.$message({
          type: "warning",
          message: "请选择项目部！",
        })
      } else {
        this.queryParams.recordIds = this.tableData.map(item => item.id)
        this.queryParams.time = this.form.securityDate || this.$route.query.day
        const res1 = await getRevisePeople({
          projectId: this.$store.state.app.selectData,
          hiddenTrouble: "0",
        })
        this.revisePeopleList = res1.rows || []
        const res2 = await getTree({ checkTypeNo: null })
        this.deptOptions = res2.data || []
        this.title = "添加巡检记录"
        this.dialogVisible = true
        this.getlistLogFun()
      }
    },
    //获取巡查记录列表
    getlistLogFun () {
      this.addtableData = []
      getlistLog(this.queryParams).then((res) => {
        this.addtableData = res.rows || []
        this.total = res.total || 0
      })
    },
    //重置
    resetFun () {
      this.queryParams.pageNum = 1
      this.queryParams.checkType = null
      this.queryParams.dataStatus = ''
      this.queryParams.checkPeopleId = ''
      this.getlistLogFun()
    },

    handleSelectionChange (val) {
      this.beforTableData = val.map((item) => item)
    },
    //确定
    async submitTable () {
      this.tableData = [...this.tableData, ...this.beforTableData]
      this.dialogVisible = false
    },
    // 查看隐患详情
    listLook (row) {
      this.selectRow = row
      this.innerVisible = true
    },
    delRow (row) {
      this.tableData = this.tableData.filter((item) => item.id !== row.id)
    },
    submitForm () {
      if (this.$route.query.id != null) {
        this.form.securityType = this.$route.query.securityType
        this.form.recordIds = this.tableData.map((item) => item.id)
        this.form.projectId = this.$store.state.app.selectData
        this.form.time = this.$route.query.day
        this.form.weather = this.watcher.weather
        const picList = this.form.attachList || []
        const urlList = []
        picList.forEach(e => {
          urlList.push(e.url)
        })
        this.form.secnePhoto = urlList.join(',')
        updateLog(this.form).then((data) => {
          this.$message({
            type: "success",
            message: "提交成功！",
          })
          this.$router.push({ name: "Log" })
        })
      } else {
        if (JSON.stringify(this.form) !== "{}" || this.ids != []) {
          this.form.securityType = this.$route.query.securityType
          this.form.recordIds = this.tableData.map((item) => item.id)
          this.form.projectId = this.$store.state.app.selectData
          this.form.time = this.$route.query.day
          this.form.watcher = this.watcher.weather
          const picList = this.form.attachList || []
          const urlList = []
          picList.forEach(e => {
            urlList.push(e.url)
          })
          this.form.secnePhoto = urlList.join(',')
          upData(this.form).then((data) => {
            this.$message({
              type: "success",
              message: "提交成功！",
            })
            this.$router.push({ name: "Log" })
          })
        } else {
          this.$message({
            type: "error",
            message: "请填写后再提交！",
          })
        }
      }
    },
  },
  computed: {
    ...mapState(["app"]),
    isToday () {
      const date = this.form.securityDate || this.$route.query.day
      const today = this.parseTime(new Date(), "{y}-{m}-{d}")
      const res = (date == today)
      if (res) {
        this.getWatchers()
      }
      return res
    },
  },
  watch: {
    app: {
      handler (newVal, oldVal) {
        this.queryParams.projectId = newVal.selectData
      },
      deep: true,
    },
    $route: {
      handler (newVal, oldVal) {
        // this.getWatchers();
        if (newVal.name != "addLog") {
          return
        }
        this.form = {}
        this.tableData = []
        this.mode = this.$route.query.mode
        if (this.$route.query.id != null) {
          getLog(this.$route.query.id).then((data) => {
            this.form = data.data.bizSecurityLog
            if (this.mode == 'view') {
              this.generatePreviewList()
            }
            this.tableData = data.data.bizProjectCheckRecord
          })
        }
      },
      deep: true,
    },
  },
  created () {
    this.form = {}
    this.tableData = []
    // this.getWatchers();
    this.mode = this.$route.query.mode
    if (this.$route.query.id != null) {
      getLog(this.$route.query.id).then((data) => {
        this.form = {}
        this.form = data.data.bizSecurityLog
        if (this.mode == 'view') {
          this.generatePreviewList()
        }
        this.tableData = data.data.bizProjectCheckRecord
      })
    }
  },
}
</script>
<style scoped>
.previewImg {
  width: 146px;
  height: 149px;
  margin-right: 10px;
}
</style>
